const http = require('../../../util/http')
const c = require('../../../config')
const DAL = require('./DAL')
const result = {
  msg: 'user BLL [not run]',
  data: null,
  code: 40001
}
function formatResult(res) {
  if (res.msg == 'success') {
    res.code = 10000
  } else {
    res.data = null
    res.code = 40001
  }
  return res
}
module.exports = {
  // 去user服务器验证登录信息
  async userLogin( ctx ) {
    let res = result
    let b = ctx.request.body
    let url = `galaha.top/api/User/Login`
    let r = await http.httpsReq('post', url, b)
    if (r.code == 10000) {
      if (!r.wxOpenId) {
        res.msg = '无效的openId'
      } else {
        b.openId = r.wxOpenId
        b.flag = 'USER_LOGIN'
        res = await DAL.getUserByOid(b)
        res = formatResult(res)
      }
    } else {
      res.msg = r.msg
    }
    ctx.body = res
  },
  // 微信小程序登录
  async mpLogin( ctx ) {
    let res = result
    let b = ctx.request.body
    if (!b.code) {
      res.msg = '小程序鉴权失败，请重试'
    } else {
      let p = {}
      p.a = c.wxConfig.appid
			p.s = c.wxConfig.secret
			p.c = b.code
			p.t = 'authorization_code'
      let url = `api.weixin.qq.com/sns/jscode2session?appid=${p.a}&secret=${p.s}&js_code=${p.c}&grant_type=${p.t}`
      let r = await http.httpsReq('post', url, null)
      if (r && r.openid && r.session_key) {
        res = await DAL.getUserInfo(r)
        res = formatResult(res)    
      } else {
        res.msg = '获取openid失败，请重试'
      }
    } 
    ctx.body = res
  },
  // 设置用户昵称和头像
  async setUser(ctx) {
    let res = result
    let b = ctx.request.body
    if (!b.openId) {
      res.msg = '无此用户'
    } else if (!b.name && !b.avatar) {
      res.msg = '用户信息不能为空'
    } else {
      res = await DAL.setUser(b)
      res = formatResult(res)
    }
    ctx.body = res
  },
  // 获取user列表
  async getUsers(ctx) {
    let res = result
    let q = ctx.request.query
    res = await DAL.getUsers(q)
    res = formatResult(res)
    ctx.body = res
  },
  // 按openid获取朋友列表
  async getBuddys(ctx) {
    let res = result
    let q = ctx.request.query
    res = await DAL.getBuddyByOpenId(q)
    res = formatResult(res)
    ctx.body = res
  },
  // 绑定成为朋友
  async setBuddy(ctx) {
    let res = result
    let b = ctx.request.body
    if (!b.openId) {
      res.msg = '扫码openId错误'
    } else if (!b.buddyId) {
      res.msg = '无效的二维码'
    } else {
      res = await DAL.setBuddy(b)
      res = formatResult(res)
    }
    ctx.body = res
  },
  // 删除朋友
  async delBuddy(ctx) {
    let res = result
    let b = ctx.request.body
    if (!b.openId) {
      res.msg = '本人openid错误'
    } else if (!b.buddyOId) {
      res.msg = '朋友openid错误'
    } else {
      res = await DAL.delBuddy(b)
      res = formatResult(res)
    }
    ctx.body = res
  }
}